package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"mall-go/common"
	"mall-go/dto"
	"mall-go/repository"
	"mall-go/response"
	"strconv"
)

const (
	DoneOrder  = 2
	OutOrder   = 3
	CloseOrder = -3
)

type OrderController struct {
	db *gorm.DB
}

// List 查询商品列表
func (receiver OrderController) List(ctx *gin.Context) {
	//获取分页数据
	pageNumber, _ := strconv.Atoi(ctx.Query("pageNumber"))
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	orderNo := ctx.Query("orderNo")
	orderStatus := ctx.Query("orderStatus")
	if pageNumber < 1 || pageSize < 10 {
		panic("分页参数异常")
	}
	pageDTO := dto.OrderPageDTO{
		Page:  pageNumber,
		Limit: pageSize,
		Start: (pageNumber - 1) * pageSize,
	}
	if orderNo != "" {
		//这里把keyword当成商品名称就行了，不想再重新写一个dto
		pageDTO.OrderNO = orderNo
	}
	//这里没有想到有什么很好的处理零值的方案
	if orderStatus != "" {
		status, _ := strconv.Atoi(orderStatus)
		pageDTO.OrderStatus = status
	} else {
		//这里暂时先将他赋值为-1作为未赋值的标识
		pageDTO.OrderStatus = -1
	}
	orderRepo := repository.NewMallOrderRepo()
	page := orderRepo.GetNewBeeMallOrdersPage(pageDTO)
	response.Success(ctx, gin.H{"ordersVO": page}, "Success")
}

// OrderDetailPage 订单详情
func (receiver OrderController) OrderDetailPage(ctx *gin.Context) {
	orderId, _ := strconv.Atoi(ctx.Params.ByName("orderId"))
	orderRepo := repository.NewMallOrderRepo()
	detailVO := orderRepo.GetOrderDetailByOrderId(orderId)
	response.Success(ctx, gin.H{"orderDetail": detailVO}, "Success")
}

// CheckDone 配货
func (receiver OrderController) CheckDone(ctx *gin.Context) {
	var ids dto.BatchIdParam
	ctx.Bind(&ids)
	if len(ids.UserIds) == 0 {
		panic("参数异常")
	}
	//执行配货操作
	orderRepo := repository.NewMallOrderRepo()
	done := orderRepo.CheckOrders(ids, DoneOrder)
	if done == "Success" {
		response.Success(ctx, nil, "配货成功")
		return
	}
	response.Failure(ctx, nil, done)
}

// CheckOut 修改订单为已出库
func (receiver OrderController) CheckOut(ctx *gin.Context) {
	var ids dto.BatchIdParam
	ctx.Bind(&ids)
	if len(ids.UserIds) == 0 {
		panic("参数异常")
	}
	//执行出库操作
	orderRepo := repository.NewMallOrderRepo()
	flag := orderRepo.CheckOrders(ids, OutOrder)
	if flag == "Success" {
		response.Success(ctx, nil, flag)
		return
	}
	response.Failure(ctx, nil, flag)
}

// CloseOrder 关闭订单(批量)
func (receiver OrderController) CloseOrder(ctx *gin.Context) {
	var ids dto.BatchIdParam
	ctx.Bind(&ids)
	if len(ids.UserIds) == 0 {
		panic("参数异常")
	}
	//批量关闭订单
	orderRepo := repository.NewMallOrderRepo()
	flag := orderRepo.CheckOrders(ids, CloseOrder)
	if flag == "Success" {
		response.Success(ctx, nil, flag)
		return
	}
	response.Failure(ctx, nil, flag)
}

func NewOrderController() OrderController {
	db := common.GetDB()
	return OrderController{db: db}
}
